package com.jzrh.flashbee.common.interceptor;

import com.alibaba.fastjson2.JSONObject;
import com.jzrh.flashbee.service.IFlashbeeUserService;
import com.jzrh.flashbee.common.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author Jince
 * @since: 2023.11.22 下午 11:18
 * @description:
 */
@Component
@Slf4j
public class AuthInterceptor implements HandlerInterceptor {
    @Resource
    private IFlashbeeUserService flashbeeUserService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String access_key=request.getHeader("Access-Key");
        String username=request.getHeader("UserName");
        if(StringUtils.isNotEmpty(access_key)&&StringUtils.isNotEmpty(username)){
            if(flashbeeUserService.existAccessKey(access_key, username)){
                return true;
            }
        }
        returnJson(response,JSONObject.toJSONString(Result.error("对不起，您没有权限生成短网址")));
        return false;
    }
    private void returnJson(HttpServletResponse response, String json) throws Exception{
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=utf-8");
        try (PrintWriter writer = response.getWriter()) {
            writer.print(json);
        } catch (IOException e) {
            log.error("response error", e);
        }
    }
}
